<?php
class Register extends Controller {

	function Register(){
		parent::Controller();	
	}
	function getEmail(){
		$nim = $this->input->post('nim');
		$this->load->model('Mahasiswa');
		$sendMail = $this->sendMail($nim);
		if($sendMail->success){
			echo $this->Mahasiswa->isIlkomers($nim);
		}else{
			$result['ok'] = FALSE;
			$result['error'] = $sendMail->error;
			echo json_encode($result);
		}
	}
	function sendMail($nim){
		$result->success = TRUE;
		$result->error ='';
		$this->load->model('Mahasiswa');
		$this->load->model('User');
		$return = json_decode($this->Mahasiswa->isIlkomers($nim));
		if($return->ok){
			srand ((double) microtime( )*1000000);
			$random_number = rand( );
			$linkConfirm = md5($random_number.'isee');
			$mid = $return->id;
			$user = json_decode($this->User->insertnewuser($mid,$linkConfirm));
			if(!$user->ketersediaan){
				$result->success = FALSE;
				$result->error = 'Anda sudah melakukan registrasi sebelumnya, silakan cek email anda';
			}else{
				$message = "Selamat Datang di I-See, Situs Jejaring Sosial\n
				Silakan Klik Link Konfirmasi di bawah ini \n
				".base_url()."registrasi/index/".$user->id."/".$linkConfirm."\n
				\n
				I-See Team";
				$subject = "I-See Link Confirmation";
				$email = $return->email;
				$from	= 'I-See Team'.' <'.'ilkomersee@gmail.com'.'>';	
				if (email_send($from , $email, $subject, $message)){
					$result->success = TRUE;
				}else{
					$result->success = FALSE;
					$result->error ='Email Gagal Dikirim';
				}	
			}
				
		}else{
			$result->success = FALSE;
			$result->error ='Anda Bukan Ilkomers';
		}
		return $result;
	}
	
	function finishRegister(){
		$uid = $this->input->post('uid');
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		$this->load->model('InsertProfile');		
		$return = json_decode($this->InsertProfile->insertData($uid,
			$username,
			md5($password)));

		if($return->instProfile){
			//echo "Berhasil";
			$this->load->model('User');
			$this->User->setRegLogDate($uid);
			$userData = array(
               	'userId'  => $uid,
           		'isLogin' => TRUE
             );
			$this->session->set_userdata($userData);
			redirect('/dashboard');
			//redirect login
		}else{
			echo "Gagal Update";
			//redirect halaman register
		}
	}
	
	function usernameChecker(){
		$username = $this->input->post('username');
		$this->load->model('User');
		$takenUsername = $this->User->usernameIsUsed();
		if(in_array($username,$takenUsername)){
			echo json_encode(FALSE);
			exit;
		}
		echo json_encode(TRUE);
	}
}